const createError = require('http-errors');

const express = require('express');
const path = require('path');

const cookieParser = require('cookie-parser');
const logger = require('morgan');//记录日志中间件
const session = require('./routes/session') //加载路由器
const routes = require('./routes/routes')

const app = express();

// 查看引擎设置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));//以将请求信息打印在控制台
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use('/public/', express.static(path.join(__dirname, 'public')))  //开放服务器中public文件夹
app.use('/node_modules/', express.static('./node_modules/')) //开放服务器中node_modules文件夹



//配置解决跨域
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
})


app.use(session);
app.use(routes);
// 捕获404并转发到错误处理程序
app.use(function (req, res, next) {
  next(createError(404));
});

//错误处理程序
app.use(function (err, req, res, next) {
  // //设置局部变量，只提供开发错误
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // 呈现错误页
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
